package com.xy.job.executor.core.client

import com.xy.job.core.api.request.HeartbeatParam
import com.xy.job.core.api.request.JobFeedbackParam
import com.xy.job.core.api.response.ResponseWrapper
import com.xy.job.executor.log.LoggerFactory
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.runBlocking

class DefaultAdminClient(
    private var adminHost: String,
    private var adminPort: Int,
) : IAdminClient {

    val logger = LoggerFactory.getLogger(DefaultAdminClient::class.java)

    private val client: HttpClient = HttpClient(CIO) {
        expectSuccess = true
        install(Logging) {
            this.level = LogLevel.NONE
        }
        install(ContentNegotiation) {
            json()
        }
        defaultRequest {
            host = adminHost
            port = adminPort
            url { protocol = URLProtocol.HTTP }
        }
    }

    override fun heartbeat(param: HeartbeatParam): ResponseWrapper<Boolean> {
        return runBlocking {
            val result = client.post("/private/api/admin/heartbeat") {
                contentType(ContentType.Application.Json)
                setBody(param)
            }
            result.body()
        }
    }

    override fun feedback(param: JobFeedbackParam): ResponseWrapper<Boolean> {
        return runBlocking {
            val result = client.post("/private/api/admin/feedback") {
                contentType(ContentType.Application.Json)
                setBody(param)
            }
            result.body()
        }
    }

    override fun removeRegister(): ResponseWrapper<Boolean> {
        return runBlocking {
            val result = client.post("/private/api/admin/removeRegister") {
                contentType(ContentType.Application.Json)
            }
            result.body()
        }
    }

}